<template>
    <div class="edit-post">
        <el-form class="edit-panel" :model="formData" :rules="rules" ref="formDataRef" label-width="60px"
            @submit.prevent>
            <!-- 编辑器 -->
            <div class="post-editor">
                <el-card>
                    <template #header>
                        <div class="post-editor-title">
                            <span>正文</span>
                            <div class="change-editor-type">
                                <span class="iconfont icon-change" @click="changeEditor">
                                    切换为{{ editorType ? "富文本编辑器" : "markdown编辑器" }}
                                </span>
                            </div>
                        </div>
                    </template>

                    <el-form-item prop="content" label-width="0">
                        <EditorHtml :height="htmlEditorHeight" v-if="editorType == 0" v-model="formData.content">
                        </EditorHtml>
                        <EditorMarkdown v-if="editorType == 1" :height="markdownHeight"
                            v-model="formData.markdownContent" @htmlContent="setHtmlContent">
                        </EditorMarkdown>
                    </el-form-item>

                </el-card>
            </div>
            <!-- 设置 -->
            <div class="post-setting">
                <el-card>
                    <template #header>
                        <span>设置</span>
                    </template>
                    <div class="setting-inner">
                        <el-form-item label="标题" prop="title">
                            <el-input clearable placeholder="提示信息" v-model="formData.title"></el-input>
                        </el-form-item>
                        <el-form-item label="板块" prop="boardIds">
                            <el-cascader :options="boardList" v-model="formData.boardIds" clearable :props="boardProps"
                                placeholder="请选择板块" style="width: 100%;">
                            </el-cascader>

                        </el-form-item>
                        <el-form-item label="封面" prop="cover">
                            <CoverUpload v-model="formData.cover"></CoverUpload>
                        </el-form-item>

                        <el-form-item label="摘要" prop="summary">
                            <el-input clearable placeholder="提示信息" v-model="formData.summary" :rows="5" maxlength="150"
                                type="textarea"></el-input>
                        </el-form-item>

                        <el-form-item label="附件" prop="attachment">
                            <AttachmentSelector v-model="formData.attachment"></AttachmentSelector>
                        </el-form-item>

                        <el-form-item label="积分" prop="integral">
                            <!--input输入-->
                            <el-input clearable placeholder="请输入积分" v-model="formData.integral"></el-input>
                            <span class="tips">附件所需积分，0积分表示无需积分下载</span>
                        </el-form-item>

                        <el-form-item label="" prop="">
                            <el-button @click="postHandler" style="width: 100%;" type="primary">保存</el-button>
                        </el-form-item>
                    </div>

                </el-card>
            </div>
        </el-form>
    </div>
</template>

<script setup>
import { valueEquals } from 'element-plus';
import message from '@/utlis/Message';
import { ref, reactive, getCurrentInstance, nextTick, watch } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { ElMessageBox } from 'element-plus'
const { proxy } = getCurrentInstance();
const route = useRoute();
const router = useRouter();

const api = {
    loadBoard4Post: '/forum/loadBoard4Post',
    postArticle: '/forum/postArticle',
    articleDetail4Update: '/forum/articleDetail4Update',
    updateArticle: '/forum/updateArticle',
}

const articleId = ref();
const getArticleDetail = () => {
    nextTick(async () => {
        formDataRef.value.resetFields();
        // 修改
        if (articleId.value) {
            let res = await proxy.Request({
                url: api.articleDetail4Update,
                params: {
                    articleId: articleId.value
                },
                showError: false,
                errorCallback: (response) => {
                    console.log(response);

                    ElMessageBox.alert(response.msg, '错误', {
                        "show-close": false,
                        callback: (action) => {
                            router.go(-1)
                        },
                    })
                }
            })
            if (!res) {
                return;
            }
            let articleInfo = res.data.forumArticle;
            // 设置编辑器
            editorType.value = articleInfo.editorType;
            // 设置板块信息
            articleInfo.boardIds = [];
            articleInfo.boardIds.push(articleInfo.pBoardId);
            if (articleInfo.boardId != null && articleId.boardId != 0) {
                articleInfo.boardIds.push(articleInfo.boardId)
            }
            // 设置封面信息
            if (articleInfo.cover) {
                articleInfo.cover = { imageUrl: articleInfo.cover }
            }
            // 设置附件
            if (res.data.attachment) {
                articleInfo.attachment = {
                    name: res.data.attachment.fileName
                }
                articleInfo.integral = res.data.attachment.integral
            }
            formData.value = articleInfo
        }
        else {
            formData.value = {}
            editorType.value = proxy.VueCookies.get("editorType") || 0
        }
    })
}

// 设置markdown编辑器的富文本信息
const setHtmlContent = (htmlContent) => {
    formData.value.content = htmlContent;
}

watch(() => route, (newVal, oldVal) => {
    if (newVal.path.indexOf('/editPost') != -1 || newVal.path.indexOf('/newPost') != -1) {
        articleId.value = newVal.params.articleId;
        getArticleDetail();
    };
}, { immediate: true, deep: true });

const markdownHeight = window.innerHeight - 180;
const htmlEditorHeight = window.innerHeight - 225;

const formData = ref({});
const formDataRef = ref();
const rules = {
    title: [{ required: true, message: "请输入内容！" },
    { max: 20, message: '标题最长不能超过20字' }
    ],
    boardIds: [{ required: true, message: "请选择板块！" }],
    content: [{ required: true, message: "请输入正文！" }],
    summary: [{ required: true, message: "请输入摘要！" }],
    integral: [{ required: true, message: "请输入下载所需积分！" },
    { validator: proxy.Verify.number, message: "积分只能是数字" }
    ]
};

const postHandler = () => {
    formDataRef.value.validate(async (valid) => {
        if (!valid) {
            return;
        }
        let params = {};
        Object.assign(params, formData.value);
        console.log(params.boardIds);

        //设置板块ID
        if (params.boardIds.length == 1) {
            params.pBoardId = params.boardIds[0]
        } else if (params.boardIds.length == 2) {
            params.pBoardId = params.boardIds[0]
            params.boardId = params.boardIds[1]
        }

        console.log(params.pBoardId, params.boardId);

        delete params.boardIds;
        // 设置编辑器类型
        params.editorType = editorType.value
        //获取文章内容
        const contentText = params.content.replace(/<(?!img).*?>/g, "")
        if (contentText == '') {
            proxy.message.warning("正文不能为空！")
        }
        if (params.attachment != null) {
            params.attachmentType == 1;
        } else {
            params.attachmentType == 0;
        }
        // 封面
        if (!(params.cover instanceof File)) {
            delete params.cover
        }

        // 附件
        if (!(params.attachment instanceof File)) {
            delete params.attachment
        }
        console.log(params);

        // 发送请求
        let result = await proxy.Request({
            url: params.articleId ? api.updateArticle : api.postArticle,
            params: params
        })
        if (!result) {
            return;
        }
        message.success("保存成功");
        router.push(`/post/${result.data}`)
    })
}

// 板块信息
const boardList = ref([]);
const boardProps = {
    multiple: false,
    checkStrictly: true,
    value: "boardId",
    label: "boardName"
}
const loadBoardList = async () => {
    let result = await proxy.Request({
        url: api.loadBoard4Post,
    })
    if (!result) {
        return;
    }
    boardList.value = result.data
}
loadBoardList();

// 编辑器类型 0：富文本 1：markdown
const editorType = ref(null)

const changeEditor = () => {
    proxy.Confirm("切换编辑器会清空当前正在编辑的内容，确定要切换吗？", () => {
        editorType.value = editorType.value == 1 ? 0 : 1;
        formData.value.content = '';
        formData.value.markdownContent = '';
        proxy.VueCookies.set("editorType", editorType.value, -1)
    })

}
</script>

<style lang="scss">
.edit-post {
    .edit-panel {
        display: flex;

        .el-card__header {
            padding: 10px;
        }

        .post-editor {
            flex: 1;

            .post-editor-title {
                display: flex;
                justify-content: space-between;

                .iconfont {
                    font-size: 14px;
                    cursor: pointer;
                    color: var(--link);
                }
            }
        }

        .post-setting {
            margin-left: 10px;
            width: 450px;

            .setting-inner {
                max-height: calc(100vh - 170px);
                overflow: auto;

                .tips {
                    color: #969494;
                }
            }
        }
    }

    .el-form-item {
        align-items: flex-start;
    }
}
</style>
